package arrAndstr;

import static sun.plugin2.main.server.LiveConnectSupport.getResult;

/*
	129. 求根节点到叶节点数字之和
	思考：
		为什么用StringBuffer就会出错？ --> StringBuffer 递归过程中被所有分支共享，需要回溯
	优化：
		用int，每次 n = n*10 + root.val
		而不是 s = s + root.val
 */
public class T129 {

	static class TreeNode {
		int val;
		TreeNode left;
		TreeNode right;

		TreeNode() {
		}

		TreeNode(int val) {
			this.val = val;
		}

		TreeNode(int val, TreeNode left, TreeNode right) {
			this.val = val;
			this.left = left;
			this.right = right;
		}
	}

	public static void main(String[] args) {
		TreeNode node = new TreeNode(4);
		node.left = new TreeNode(9);
		node.left.left = new TreeNode(5);
		node.left.right = new TreeNode(1);
		node.right = new TreeNode(0);

		int r = sumNumbers(node);

		System.out.println(r);
	}

	public static int sumNumbers(TreeNode root) {
		int result = 0;
		// getResult
		result = getResult(root, "");

		return result;
	}

	private static int getResult(TreeNode root, String s) {
		if (root == null) return 0;

		s = s + root.val;

		if (root.left == null && root.right == null) {
			return Integer.parseInt(s.toString());
		}

		return getResult(root.left, s) + getResult(root.right, s);
	}
}
